<?php
/**
 * ***********************************************************************************
 * 咨询鲤-知识商城PC端店铺
 * 
 * 验证商户是否具有PC端店铺权限
 * 
 * @author Mr.RJH
 * @date 2025-09-9
 * @email<15213026209@163.com>
 * ***********************************************************************************
 */
namespace app\middleware;

use think\Request;
use think\exception\HttpResponseException;

use app\model\merchant\ZxlMerchantModel;
use app\model\merchant\ZxlMerchantMenuModel;
use app\model\merchant\ZxlMerchantApplyModel;
use app\model\merchant\ZxlMerchantVersionModel;
use app\model\merchant\ZxlMerchantUpgradeOrderModel;
use app\model\merchant\ZxlKnowStorePcSettingModel;
use app\model\merchant\ZxlKnowStorePcPageModel;
use app\model\merchant\ZxlKnowStoreSettingModel;
use app\model\merchant\ZxlKnowStoreWeixinMiniprogramAuthorizeModel;
use app\model\merchant\ZxlKnowStorePcSelfDomainModel;

class MerchantVerify
{
    public function handle(Request $request, \Closure $next)
    {
        $desc = '很抱歉，当前域名商户暂未开通咨询鲤PC端店铺！';
        // 获取当前域名
        $domain = $request->host();
        
        $m_id = '';
        // 获取商户PC端店铺配置信息
        $set = ZxlKnowStorePcSettingModel::where('domain_url', $domain)->find();
        if ($set) {
            $m_id = $set['m_id'];
        }
        // 获取独立域名
        $self = ZxlKnowStorePcSelfDomainModel::where('domain', $domain)->find();
        if ($self) {
            $m_id = $self['m_id'];
        }
        if ($set == '' && $self == '') {
           $this->http404($desc, 4);
        } else {
            $pc_info = ZxlKnowStorePcSettingModel::where('m_id', $m_id)->find();
            // 继续验证商户是否包含权限
            $merchant = ZxlMerchantModel::where('id', $m_id)->find();
            $is_know_store_pc_auth = $this->is_module_auth($merchant, '484');
            if (!$is_know_store_pc_auth) {
                $this->http404($desc, 4);
            }

            $pc_info['store_name'] = $merchant['nickname'];
            if ($pc_info['nav_list']) {
                $nav_list = json_decode($pc_info['nav_list'], true);
                foreach ($nav_list as &$v) {
                    $page = ZxlKnowStorePcPageModel::find($v['page_id']);
                    $v['href'] = $page['path_url'];
                    $v['controller'] = $page['controller'];
                }
                $pc_info['nav_list'] = $nav_list;
            }
            if ($pc_info['footer_nav_list']) {
                $pc_info['footer_nav_list'] = json_decode($pc_info['footer_nav_list'], true);
            }

            $applet_qrcode = ZxlKnowStoreWeixinMiniprogramAuthorizeModel::where(['m_id' => $m_id, 'is_remove' => 0])->value('qrcode_url');
            $pc_info['applet_qrcode'] = $applet_qrcode ? $applet_qrcode : '/static/images/no_pic.png';

            // 获取商户店铺设置信息
            $store_set = ZxlKnowStoreSettingModel::where('m_id', $m_id)->field('service_open,service_info,privacy_agreement,user_agreement')->find();
            if ($store_set) {
                $store_set['service_info'] = json_decode($store_set['service_info'], true);
            }
        }
        
        // 将商户信息设置为请求对象的属性，使其在整个请求生命周期内可用
        $request->m_id = $m_id;
        $request->pc_info = $pc_info; // PC端店铺信息
        $request->self = $self;
        $request->store_set = $store_set; // 店铺设置

        return $next($request);
    }

    /**
     * 商户是否含有对应板块权限
     * 
     * @param array $merchant
     * @param string $auth_id
     * @return int
     */
    private function is_module_auth($merchant, $auth_id)
    {
        $is_contain_auth = 0;
        // 商户版本权限
        $version_rules = ZxlMerchantVersionModel::where('id', $merchant['version_id'])->value('rules');
        $rules = explode(',',$version_rules);

        // 是否定制权限
        if ($merchant['auth_menu_ids']) {
            $rules = explode(',',$merchant['auth_menu_ids']);
        }

        // 获取购买功能服务权限(未过期的)
        $upgrade_order = ZxlMerchantUpgradeOrderModel::where(['order_status' => 1, 'apply_type' => 2, 'm_id' => $merchant['id']])->where('effective_time', '>', time())->select()->toArray();
        
        if ($upgrade_order) {
            foreach ($upgrade_order as $v) {
                // 获取应用服务关联菜单ID
                $menu_id = ZxlMerchantApplyModel::where('id', $v['apply_id'])->value('menu_id');
                if ($menu_id) {
                    array_push($rules, (string)$menu_id);
                }
                
                // 获取菜单是否包含在目录里
                $parent_menu_id = ZxlMerchantMenuModel::where('id', $menu_id)->value('pid');
                if ($parent_menu_id) {
                    array_push($rules, (string)$parent_menu_id);
                }
                
                // 获取目录应用下所有菜单
                $directory_all_menu = ZxlMerchantMenuModel::where(['pid' => $menu_id, 'is_apply' => 0])->select()->toArray();
                foreach ($directory_all_menu as $val) {
                    array_push($rules, (string)$val['id']);
                    // 获取子菜单
                    $child_all_menu = ZxlMerchantMenuModel::where(['pid' => $val['id'], 'is_apply' => 0])->select()->toArray();
                    if ($child_all_menu) {
                        foreach ($child_all_menu as $value) {
                            array_push($rules, (string)$value['id']);
                        }
                    }
                }
            }
        }
        $rules = array_unique($rules);
        if (in_array($auth_id, $rules)) {
            $is_contain_auth = 1;
        }
        
        return $is_contain_auth;
    }

    /**
     * 404异常页面
     * 
     * @param string $desc
     * @return string
     */
    private function http404($desc='', $firstDigit)
    {
        exit('
            <style>
                .error {display: grid;place-items: center;height: 98vh;}
                .error .clip .shadow {height:180px;}
                .error .clip:nth-of-type(2) .shadow {width:130px;}
                .error .clip:nth-of-type(1) .shadow,.error .clip:nth-of-type(3) .shadow {width:250px;}
                .error .digit {width:150px;height:150px;line-height:150px;font-size:120px;font-weight:bold;}
                .error h2 {font-size:32px;}
                .error .msg {top:-190px;left:30%;width:80px;height:80px;line-height:80px;font-size:32px;}
                .error span.triangle {top:70%;right:0%;border-left:20px solid #535353;border-top:15px solid transparent;border-bottom:15px solid transparent;}
                .error .container-error-404 {position:relative;height:250px;}
                .error .container-error-404 .clip {display:inline-block;transform:skew(-45deg);}
                .error .clip .shadow {overflow:hidden;}
                .error .clip:nth-of-type(2) .shadow {overflow:hidden;position:relative;box-shadow:inset 20px 0px 20px -15px rgba(150,150,150,0.8),20px 0px 20px -15px rgba(150,150,150,0.8);}
                .error .clip:nth-of-type(3) .shadow:after,.error .clip:nth-of-type(1) .shadow:after {content:"";position:absolute;right:-8px;bottom:0px;z-index:9999;height:100%;width:10px;background:linear-gradient(90deg,transparent,rgba(173,173,173,0.8),transparent);border-radius:50%;}
                .error .clip:nth-of-type(3) .shadow:after {left:-8px;}
                .error .digit {position:relative;top:8%;color:white;background:#16b777;border-radius:50%;display:inline-block;transform:skew(45deg);}
                .error .clip:nth-of-type(2) .digit {left:-10%;}
                .error .clip:nth-of-type(1) .digit {right:-20%;}
                .error .clip:nth-of-type(3) .digit {left:-20%;}
                .error h2 {font-size:22px;color:#A2A2A2;font-weight:bold;padding-bottom:20px;}
                .error .tohome {font-size:16px;color:#07B3F9;}
                .error .msg {position:relative;z-index:98;display:block;background:#535353;color:#A2A2A2;border-radius:50%;font-style:italic;}
                .error .triangle {position:absolute;z-index:999;transform:rotate(45deg);content:"";width:0;height:0;}
                @media(max-width:767px) {.error .clip .shadow {height:100px;}
                    .error .clip:nth-of-type(2) .shadow {width:80px;}
                    .error .clip:nth-of-type(1) .shadow,.error .clip:nth-of-type(3) .shadow {width:100px;}
                    .error .digit {width:80px;height:80px;line-height:80px;font-size:52px;}
                    .error h2 {font-size:18px;}
                    .error .msg {top:-110px;left:15%;width:40px;height:40px;line-height:40px;font-size:18px;}
                    .error span.triangle {top:70%;right:-3%;border-left:10px solid #535353;border-top:8px solid transparent;border-bottom:8px solid transparent;}
                    .error .container-error-404 {height:150px;}
                }
            </style>
            <div class="error">
                <div class="container-floud">
                    <div style="text-align: center">
                        <div class="container-error-404">
                            <div class="clip">
                                <div class="shadow">
                                    <span class="digit thirdDigit">4</span>
                                </div>
                            </div>
                            <div class="clip">
                                <div class="shadow">
                                    <span class="digit secondDigit">0</span>
                                </div>
                            </div>
                            <div class="clip">
                                <div class="shadow">
                                    <span class="digit firstDigit">'.$firstDigit.'</span>
                                </div>
                            </div>
                            <div class="msg">OH!
                                <span class="triangle"></span>
                            </div>
                        </div>
                        <h2 class="h1">'.$desc.'</h2>
                    </div>
                </div>
            </div>
        ');
    }

}